<?php
class BaseModelXML {
    /**
     * xml document to array
     * @param string document $xml
     * @return mixed array
     */
	public static function XML2Array($xml) {
		   $parser = xml_parser_create('UTF-8'); 
		   xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
		   xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
		   xml_parse_into_struct($parser, $xml, $vals);
		   xml_parser_free($parser);
			
		   $_tmp = '';
		   foreach ( $vals as $_elem ) {
				$_tag   = $_elem['tag'];
				$_level = $_elem['level'];
				$_type  = $_elem['type'];
				if( $_level != 1 && $_type == 'close' ) {
					if( isset($multiKey[$_tag][$_level]) ) {
						$multiKey[$_tag][$_level] = 1;
					}
					else {
						$multiKey[$_tag][$_level] = 0;
					}
				}
				if ($_level!=1 && $_type == 'complete') {
					if ($_tmp == $_tag) {
						$multiKey[$_tag][$_level] = 1;
					}
					$_tmp = $_tag;
				}
			}
			foreach( $vals as $_elem ) {
				$_tag = $_elem['tag'];
				$_level = $_elem['level'];
				$_type = $_elem['type'];
				if ($_type == 'open') {
					$level[$_level] = $_tag;
				}
				$startLevel = 1;
				$str = '$ret';
				if ($_type == 'close' && $_level != 1 ) {
					$multiKey[$_tag][$_level]++;
				}
				while($startLevel < $_level) {
					  $str .= '[$level['.$startLevel.']]';
					  if (isset($multiKey[$level[$startLevel]][$startLevel]) && $multiKey[$level[$startLevel]][$startLevel]) {
						  $str .= '['.($multiKey[$level[$startLevel]][$startLevel]-1).']';
					  }
					  $startLevel++;
				}
				$add='';
				if (isset($multiKey[$_tag][$_level]) && $multiKey[$_tag][$_level] && ($_type=='open' || $_type=='complete')) {
					if (!isset($multiKey2[$_tag][$_level])) {
						$multiKey2[$_tag][$_level]=0;
					}
					else {
						$multiKey2[$_tag][$_level]++;
					}
					$add='['.$multiKey2[$_tag][$_level].']';
				}
				if (isset($_elem['value']) && trim($_elem['value'])!='' && !array_key_exists('attributes',$_elem)) {
					if ($_type == 'open')
						$str_main=$str.'[$_type]'.$add.'[\'content\'] = $_elem[\'value\'];';
					else
						$str_main=$str.'[$_tag]'.$add.' = $_elem[\'value\'];';
					eval($str_main);
				}
				if (array_key_exists('attributes',$_elem)) {
					if (isset($_elem['value'])) {
						$str_main=$str.'[$_tag]'.$add.'[\'content\'] = $_elem[\'value\'];';
						eval($str_main);
					}
					foreach ($_elem['attributes'] as $key => $value) {
						$str_att=$str.'[$_tag]'.$add.'[$key] = $value;';
						eval($str_att);
					}
				}
			}
			return $ret;
	}
}
?>